import { nextTick, ref, Ref } from "vue";

interface TriggerContext {
  range: Range;
  keyword: string;
  selection: Selection;
}

export function useTrigger(Ait: Ref, AitVal: Ref) {
  let PersonList = ref([]);

  function ReSet() {
    Ait.value = false;
    AitVal.value = "";
  }

  // 处理触发事件
  async function HandelTrigger(text: string, cursorPosition: number, context: TriggerContext) {
    let NeedTrigger = false;
    // 检查@提及
    if (ShouldTrigger(text, cursorPosition, "@")) {
      const keyword = ExtractKeyword(text, cursorPosition, "@");
      if (keyword !== null) {
        await HandleMention({ ...context, keyword });
        NeedTrigger = true;
      }
    }
    if (!NeedTrigger) ReSet();
    return NeedTrigger;
  }

  // 判断是否触发事件
  function ShouldTrigger(text: string, cursorPosition: number, triggerSymbol: string): boolean {
    const searchStr = text.slice(0, cursorPosition);
    const pattern = new RegExp(`\\${triggerSymbol}([^\\${triggerSymbol}]*)$`);
    return pattern.test(searchStr);
  }

  // 处理@
  async function HandleMention(context: TriggerContext) {
    if (PersonList.value.length === 0) {
      const res = context.range.getBoundingClientRect();
      Ait.value = true;
      AitVal.value = context.keyword;
      await nextTick(() => {
        const dom = document.getElementById("AitMention") as HTMLElement;
        dom.style.position = "fixed";
        dom.style.height = "auto";
        dom.style.maxHeight = "190px";
        dom.style.left = `${res.x - 20}px`;
        dom.style.top = `${res.y - (dom.offsetHeight + 5)}px`;
      });
      return;
    }
    ReSet();
  }

  // 提取触发词
  function ExtractKeyword(text: string, cursorPosition: number, triggerSymbol: string) {
    const searchStr = text.slice(0, cursorPosition);
    const pattern = new RegExp(`\\${triggerSymbol}([^\\${triggerSymbol}]*)$`);
    const matches = pattern.exec(searchStr);
    return matches && matches.length > 1 ? matches[1] : null;
  }

  return {
    ShouldTrigger,
    HandleMention,
    ExtractKeyword,
    HandelTrigger,
    ReSet,
  };
}
